import { Sequelize, sequelize, Task, Progress, Document, User } from '../models'
import { findGroupStudents } from './group'
import { findAllTaskProgresses } from './progress'
import CONFIG from '../config'
import kue from 'kue'
import { sendNotifications } from './notification'

var queue = kue.createQueue({ redis: CONFIG.redis })

queue.process('group_progress', async function(job, done) {
  await sequelize.transaction(
    {
      isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
    },
    async t => {
      let taskId = job.data.taskId

      let task = await Task.findById(taskId, { transaction: t })
      if (!task.groupId) {
        return
      }
      let progresses = await findAllTaskProgresses(taskId, { transaction: t })

      let excludeUserIds = progresses.map(function(item, index, array) {
        return item.userId
      })
      // exclude task owner
      excludeUserIds.push(task.ownerId)
      let users = await findGroupStudents(task.groupId, excludeUserIds, 10000)

      let newProgresses = users.map(function(item, index, array) {
        return {
          subTaskCount: task.subTaskCount,
          expireAt: task.expireAt,
          state: 'start',
          userId: item.id,
          taskId: taskId,
          documentId: task.documentId,
          versionId: task.versionId,
          groupId: task.groupId
        }
      })
      let rs = await Progress.bulkCreate(newProgresses, { transaction: t })
      let pes = await Progress.findAll({
        attributes: ['id', 'userId'],
        where: {
          taskId
        }
      })

      let targets = pes.map(p => {
        return {
          userId: p.userId,
          targetId: p.id,
          scope: 'progress'
        }
      })

      let document = await Document.findById(task.versionId)
      let title = document ? document.name : ''
      let user = await User.findById(task.ownerId)
      let userIds = await sendNotifications(
        {
          title: '作业未完成提醒',
          data: {
            keyword1: {
              value: title
            },
            keyword2: {
              value: user.nickName
            }
          },
          url: ({ targetId }) => '/pages/progress/main?isShowSideMenu=y&progressId=' + targetId
        },
        targets
      )

      return rs
    }
  )
  done()
})

/**
 * Create backgroup task to create group user progresses
 * @param {int} taskId
 */
export const createProgresses = async taskId => {
  if (!taskId) {
    throw new Error('Must specify Task ID')
  }
  queue
    .create('group_progress', {
      taskId
    })
    .delay(2000)
    .save()
}
